#！/bin/bash
#################################################################
# @Description: 用例名称：操作系统支持GM/T 0004，测试目的：验证操作系统是否支持GM/T 0002规定的密码算法运算
# @Date : 2023-11-22
# @Last Modified by :
# @Last Modified time:2023-11-25
#################################################################
set -euo pipefail
res=0
echo "1.使用SM3算法对字符串"abc"进行杂凑计算,预期输出摘要值为(stdin)= 66c7f0f462eeedd9d1f2d46bdc10e4e24167c4875cf2f7a2297da02b8f4ba8e0"
echo -n "abc" | openssl dgst -SM3 |grep "66c7f0f462eeedd9d1f2d46bdc10e4e24167c4875cf2f7a2297da02b8f4ba8e0" || res=1
echo "2.使用SM3算法对字符串"abc"进行3次杂凑计算，预期每次输出摘要值均相同"
for i in {1..3}
do 
    echo -n "abc" | openssl dgst -SM3 |grep "66c7f0f462eeedd9d1f2d46bdc10e4e24167c4875cf2f7a2297da02b8f4ba8e0" || res=1
done
echo "3.生成SM2私钥"
openssl ecparam -genkey -name SM2 -out priv.key || res=1
echo "4.生成SM2公钥"
openssl ec -in priv.key -pubout -out pub.key || res=1
echo "5.创建测试文件"
echo 'test_string' >> readme.txt
echo "6.使用SM3算法对readme.txt文件进行签名"
openssl dgst -sm3 -sign priv.key -out readme.sig readme.txt || res=1
echo "7.使用SM3公钥验证签名"
openssl dgst -sm3 -verify pub.key -signature readme.sig readme.txt || res=1
echo "8.生成另外一对公私钥，然后用不匹配的公钥pub.key签名readme2.sig进行验证，预期验证不成功"
openssl ecparam -genkey -name SM2 -out priv2.key || res=1
openssl ec -in priv2.key -pubout -out pub2.key  || res=1
openssl dgst -sm3 -sign priv2.key -out readme2.sig readme.txt || res=1
openssl dgst -sm3 -verify pub.key -signature readme2.sig readme.txt && res=1

echo "判断用例是否执行成功"
[ "$res" = "0" ] && echo -e "\033[32m-----------------test PASSED----------------\033[0m" || echo -e "\033[31m-----------------test FAILD----------------\033[0m"
echo "测试完成，开始环境清理"
rm -f priv.key sm2.sig readme.txt pub.key priv2.key pub2.key readme2.sig readme.sig